<?php
/**
 * 工程基类
 * @since   2019/10/28 创建
 * @author  ccs
 */

namespace app\app\controller;


use app\model\AdminTenant;
use app\util\ReturnCode;
use EasyWeChat\Factory;
use think\Controller;
use think\facade\Config;

class Base extends Controller {
    protected $wx = null;
    protected $config = null;
    private $debug = [];
    protected $userInfo = [];
    protected $tid = null;

    public function __construct()
    {
        parent::__construct();
        $this->userInfo = $this->request->APP_USER_INFO;
        $this->tid = $this->request->TID;
    }
    public function _initialize() {
    }
    protected function getUserTid()
    {
        return $this->tid;
    }
    protected function addTid($data){
        $data['tid'] = $this->getUserTid();
        return $data;
    }

    public function buildSuccess($data, $msg = '操作成功', $code = ReturnCode::SUCCESS) {
        $return = [
            'code' => $code,
            'msg'  => $msg,
            'data' => $data
        ];
        if ($this->debug) {
            $return['debug'] = $this->debug;
        }

        return json($return);
    }

    public function buildFailed($code, $msg, $data = []) {
        $return = [
            'code' => $code,
            'msg'  => $msg,
            'data' => $data
        ];
        if ($this->debug) {
            $return['debug'] = $this->debug;
        }

        return json($return);
    }

    protected function debug($data) {
        if ($data) {
            $this->debug[] = $data;
        }
    }
    /**
     * 懒加载获取配置
     * @return mixed|null
     */
    public function getConfig(){
        if($this->config == null){
            $this->config = Config::get('wechat.officialAccount');
            $model = AdminTenant::get($this->getUserTid());
            if($model){
                $data = $model->getData();
                $this->config['app_id'] = $data['gzh_appid'];
                $this->config['secret'] = $data['gzh_secret'];
            }
        }
        return $this->config;
    }

    /**
     * 懒加载获取easywechat操作的工厂类
     */
    public function getWx(){
        if($this->wx == null){
            $this->wx = Factory::OfficialAccount($this->getConfig());;
        }
        return $this->wx;
    }

}
